<?php
namespace Mouta\UserBundle\Controller;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\Response;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Routing\Router;


class RegistrationController extends BaseController
{
    public function registerAction(Request $request)
    {
        /** @var $session \Symfony\Component\HttpFoundation\Session\Session */
        $session = $request->getSession();
        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->container->get('fos_user.registration.form.factory');
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->container->get('fos_user.user_manager');
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->container->get('event_dispatcher');
        /** @var $securityContext \Symfony\Component\Security\Core\SecurityContext */
        $securityContext = $this->container->get('security.context');

        if ($securityContext->isGranted('ROLE_USER')) {
            $url = $this->container->get('router')->generate('home');
            return new RedirectResponse($url);
        }else{

            $user = $userManager->createUser();
            $user->setEnabled(true);
            $user->setUsername("temporal");
            $user->setCumple(new \DateTime('01/01/1982'));

            $sexovotado = $session->get('sexo_votado');
            if($sexovotado == '1')
            {
               $user->setBusco(true);
            }
            if($sexovotado == '0')
            {
              $user->setSexo(true);
            }

            $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, new UserEvent($user, $request));

            $form = $formFactory->createForm();
            $form->setData($user);

            $params = array('facet'=>'on','facet.field'=>'sexo');
            $result = $this->container->get('solr_manager')->find('*:*',0,0,$params);

            if ('POST' === $request->getMethod())
            {
                $form->bind($request);

                if ($form->isValid()) {
                    $event = new FormEvent($form, $request);
                    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

                    $userManager->updateUser($user);

                    if (null === $response = $event->getResponse()) {
                        $url = $this->container->get('router')->generate('fos_user_registration_confirmed');
                        $response = new RedirectResponse($url);
                    }

                    //$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

                    if ($request->isXmlHttpRequest())
                    {
                        $response = new Response(json_encode( array('valid'=>true, 'url'=>$this->container->get('router')->generate('fos_user_registration_check_email') )) );
                        $response->headers->set('Content-Type', 'application/json');
                        return $response;
                    } else {
                        return $response;
                    }
                } else {
                    if ($request->isXmlHttpRequest())
                    {
                        $response = new Response(json_encode( array('valid'=>false, 'errors'=>$this->getErrorMessages($form)) ));
                        $response->headers->set('Content-Type', 'application/json');
                        return $response;
                    }
                }
            }

            $seoPage = $this->container->get('sonata.seo.page');
            $seoPage
                ->setTitle('Registrarte en Amistate y conoce gente nueva')
                ->addMeta('name', 'description', 'En Amistate podes encontrar al hombres o la mujer de tus sueños')
            ;

            return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
                'form' => $form->createView(),
                'data' => $result,
            ));
        }
    }
	
	private function getErrorMessages(\Symfony\Component\Form\Form $form) {
		$errors = array();

		foreach ($form->getErrors() as $key => $error) {
				$errors[] = $error->getMessage();
		}

		foreach ($form->all() as $child) {
			if (!$child->isValid()) {
				$errors[$child->getName()] = $this->getErrorMessages($child);
			}
		}

		return $errors;
	}

    /**
     * Tell the user to check his email provider
     */
    public function checkEmailAction()
    {
        $email = $this->container->get('session')->get('fos_user_send_confirmation_email/email');
        //$this->container->get('session')->remove('fos_user_send_confirmation_email/email');
        $user = $this->container->get('fos_user.user_manager')->findUserByEmail($email);

        if (null === $user) {
            throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email));
        }

        return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:checkEmail.html.'.$this->getEngine(), array(
            'user' => $user,
        ));
    }

    /**
     * Receive the confirmation token from user email provider, login the user
     */
    public function confirmAction(Request $request, $token)
    {
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->container->get('fos_user.user_manager');

        $user = $userManager->findUserByConfirmationToken($token);

        if (null === $user) {
			return $this->container->get('templating')->renderResponse('UserBundle:Registration:confirm.html.twig', array(
				'user' => $user,
				'token' => $token,
			));
        }

        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->container->get('event_dispatcher');

        $user->setConfirmationToken(null);
        $user->setEnabled(true);

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            $url = $this->container->get('router')->generate('fos_user_registration_confirmed');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }

    /**
     * Tell the user his account is now confirmed
     */
    public function confirmedAction()
    {
        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:confirmed.html.'.$this->getEngine(), array(
            'user' => $user,
        ));
    }

}
